﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using SYSoft.Comm;
using SYSoft.Comm.Utils;
using SYSoft.Model;
using SYSoft.Model.Models.DeviceManage.StockCheck;
using SYSoft.Model.ViewModels.StockCheck;
using SYSoft.Models;
using SYSoft.Services.StockCheckManage;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace SYSoft.Controllers.StockCheckManage
{
    public class CheckDataController : BaseController
    {
        private readonly IHostingEnvironment _hostingEnvironment;
        ICheckDataService checkData;
        public CheckDataController(IHostingEnvironment hostingEnvironment, ICheckDataService checkData)
        {
            this.checkData = checkData;
            _hostingEnvironment = hostingEnvironment;
        }

        /// <summary>
        /// 消除异常
        /// </summary>
        /// <param name="key">前端组装key  ID-设备名称</param>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpPost]
        public MessageModel ChangeErrorFinish(string key, string content)
        {       
            MysqlHelper mysql = new MysqlHelper(1);
            // 更新数据库 异常处理字段 ErrorFinishResult
            string sql = $"Update dj_tasks set ErrorFinishResult='{content}',ErrorStatus=1 where Id ={Convert.ToInt32(key.Split("-")[0])}";
            if (mysql.ExecuteCommand(sql) > 0)
            {
                //先删除redis 实时异常
                var res = NetFactory.redisPool.DeleteHashKey("MTCD:STAT:ErrorStockCheck", key);
                if (!res.IsSuccess)
                    NetFactory.redisPool.DeleteHashKey("MTCD:STAT:ErrorStockCheck", key);

                return MessageModel.CreateSuccessResult();
            }
                
            return new MessageModel("更新数据库失败");
        }



        [HttpGet]
        public MessageModel<List<AlarmChecks>> GetAlarmCheckList()
        {
            var res = NetFactory.redisPool.ReadHashValues("MTCD:STAT:ErrorStockCheck");
            if (res.IsSuccess)
            {
                List<AlarmChecks> alarmChecks = new List<AlarmChecks>();
                for (int i = 0; i < res.Content.Length; i++)
                {
                    JObject obj = JObject.Parse(res.Content[i]);
                    alarmChecks.Add(new AlarmChecks
                    {
                        Id = obj.Value<int>("Id"),
                        DeviceName = obj["DeviceName"].ToString(),
                        DevicePosition = obj["DevicePosition"].ToString(),
                        TaskName = obj["TaskName"].ToString(),
                        TaskContent = obj["TaskContent"].ToString(),
                        TaskBeizhu = obj["TaskBeizhu"].ToString(),
                        OperatorPeople = obj["OperatorPeople"].ToString(),
                        StartCheckTime = Convert.ToDateTime(obj["StartCheckTime"].ToString()),
                        UploadImg = obj["UploadImg"].ToString(),

                    });
                }
                return MessageModel.CreateSuccessResult(alarmChecks);
            }
            return MessageModel.CreateFailedResult<List<AlarmChecks>>(res.Message);
        }

        /// <summary>
        /// 手动下任务
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public MessageModel HandDownTasks()
        {
            MysqlHelper mysql = new MysqlHelper(1);
            string sql1 = $"select * from dj_tasks_baselib where CreatTime>'{Convert.ToDateTime("1999-12-12 12:12:12")}'";
            DataTable dt1 = mysql.ExecuteQuery(sql1);
            List<CheckTask_Baselib> list = new List<CheckTask_Baselib>();
            if (dt1 != null && dt1.Rows.Count > 0)
            {
                for (int i = 0; i < dt1.Rows.Count; i++)
                {
                    list.Add(new CheckTask_Baselib
                    {
                        DeviceId = Convert.ToInt32(dt1.Rows[i]["DeviceId"]),
                        DeviceName = dt1.Rows[i]["DeviceName"].ToString(),
                        DevicePosition = dt1.Rows[i]["DevicePosition"].ToString(),
                        TaskContent = dt1.Rows[i]["TaskContent"].ToString(),
                        TaskName = dt1.Rows[i]["TaskName"].ToString(),
                        TaskImage = dt1.Rows[i]["TaskImage"].ToString(),
                    });
                }
                if (list.Count > 0)
                {
                    List<string> sqls = new List<string>();
                    for (int i = 0; i < list.Count; i++)
                    {
                        string sql = $"insert into dj_tasks (DeviceId,DeviceName,DevicePosition,TaskName,TaskStatus,TaskResult,TaskContent,StartCheckTime,CreatTime,TaskImage,ErrorStatus) values ({list[i].DeviceId}," +
                            $"'{list[i].DeviceName}','{list[i].DevicePosition}','{list[i].TaskName}',{0},{0},'{list[i].TaskContent}','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}'," +
                            $"'{list[i].TaskImage}',{0})";
                        sqls.Add(sql);
                    }
                    if (mysql.ExecuteCommand(sqls) == 0)
                    {
                        mysql.ExecuteCommand(sqls);
                    }
                    return MessageModel.CreateSuccessResult();
                }
                return new MessageModel("未查询到数据");
            }
            else
            {
                return new MessageModel("未查询到数据");
            }
        }



        /// <summary>
        /// 获取首页点检统计图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public MessageModel<CheckHomeChart> GetCheckChart()
        {

            MysqlHelper mysql = new MysqlHelper();
            string sql1 = $"select * from stat_stockcheck where CreatTime>='{DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd HH:mm:ss")}' and CreatTime<='{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}'";
            DataTable dt = mysql.ExecuteQuery(sql1);
            if(dt!=null && dt.Rows.Count>0)
            {
                CheckHomeChart chart = new CheckHomeChart();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    chart.Time.Add(Convert.ToDateTime(dt.Rows[i]["CreatTime"]).ToString("MM.dd"));
                    float ok = Convert.ToSingle(dt.Rows[i]["OKCount"]) / Convert.ToSingle(dt.Rows[i]["CheckTotal"]) * 100.0f;
                    chart.OKData.Add(ok);

                    float finish = Convert.ToSingle(dt.Rows[i]["CheckedCount"]) / Convert.ToSingle(dt.Rows[i]["CheckTotal"]) * 100.0f;
                    chart.FinishData.Add(finish);
                }
                return MessageModel.CreateSuccessResult(chart);
            }
            return MessageModel.CreateFailedResult<CheckHomeChart>("未查到数据");
        }

        /// <summary>
        /// 获取首页点检数量统计   
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public  MessageModel<StockCheckCount> GetCheckCount()
        {
            var res = NetFactory.redisPool.ReadKey("MTCD:STAT:StockCheck");
            if (res.IsSuccess)
            {
                StockCheckCount stock = new StockCheckCount();
                JObject obj = JObject.Parse(res.Content);
                stock.CheckTotal = Convert.ToInt32(obj["CheckTotal"].ToString());
                stock.DeviceTotal = Convert.ToInt32(obj["DeviceTotal"].ToString());
                stock.PeopleTotal = Convert.ToInt32(obj["PeopleTotal"].ToString());
                stock.CheckedCount = Convert.ToInt32(obj["CheckedCount"].ToString());
                stock.NoCheckedCount = Convert.ToInt32(obj["NoCheckedCount"].ToString());
                stock.OKCount = Convert.ToInt32(obj["OKCount"].ToString());
                stock.WarnCount = Convert.ToInt32(obj["WarnCount"].ToString());

                return MessageModel.CreateSuccessResult(stock);
            }

            return MessageModel.CreateFailedResult<StockCheckCount>("未查到数据");
        }
        /// <summary>
        /// 根据时间获取当天所有任务  
        /// </summary>
        /// <param name="time">2012-09-21</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<PageModel<Check_Task>>> GetDaliyCheckTasks(string time1, string time2, string devicename, int page, int size)
        {
            DateTime dt1 = Convert.ToDateTime(time1 + " 00:00:00");
            DateTime dt2 = Convert.ToDateTime(time2 + " 23:59:59");
            var model = await checkData.QueryPage((item => item.StartCheckTime >= dt1 && item.StartCheckTime <= dt2 && item.DeviceName == devicename), page, size);
            if (model.data != null && model.data.Count > 0)
            {
                return MessageModel.CreateSuccessResult(model);
            }
            return MessageModel.CreateFailedResult<PageModel<Check_Task>>("");
        }

        /// <summary>
        /// 根据时间获取当天所有任务
        /// </summary>
        /// <param name="devicename">2012-09-21</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<List<Check_Task>>> GetDaliyCheckTasks(string devicename)
        {
            DateTime dt1 = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00");
            DateTime dt2 = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59");
            var model = await checkData.Query(item => item.StartCheckTime >= dt1 && item.StartCheckTime <= dt2 && item.DeviceName == devicename);
            if (model != null && model.Count > 0)
            {
                return MessageModel.CreateSuccessResult(model);
            }
            return MessageModel.CreateFailedResult<List<Check_Task>>("");
        }



        [HttpPost]
        public async Task<MessageModel> UpdateCheckData([FromForm] HttpUploadDjModel model)
        {
            try
            {               
                Check_Task db = new Check_Task
                {
                    Id =model.Id,
                    DeviceId = model.DeviceId,
                    DeviceName = model.DeviceName,
                    DevicePosition = model.DevicePosition,
                    TaskName = model.TaskName,
                    TaskContent = model.TaskContent,
                    TaskImage =model.TaskImage,
                   
                    OperatorPeople =model.OperatorPeople,
                    UpdateTime =DateTime.Now,
                    TaskBeizhu =model.TaskBeizhu,
                    TaskResult =model.TaskResult,
                    TaskStatus =model.TaskStatus
                };

                if (model.UpLoadImgfile != null)
                {
                    string uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "image");
                    string uniqueFileName = Guid.NewGuid().ToString() + "_" + model.UpLoadImgfile.FileName;
                    string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                    model.UpLoadImgfile.CopyTo(new FileStream(filePath, FileMode.Create));

                    db.UploadImg = "http://localhost:8081/image/" + uniqueFileName;
                   // Console.WriteLine("点检图片路径："+db.UploadImg);
                }
               

                var res = await checkData.Update(db);
                if (res)
                    return MessageModel.CreateSuccessResult(res);
                else
                    return MessageModel.CreateFailedResult<int>("Id必须大于0");
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message);
                return MessageModel.CreateFailedResult<int>(ex.Message);
            }


        }




        // 统计分析
        /// <summary>
        /// 根据时间获取当天所有任务
        /// </summary>
        /// <param name="devicename">2012-09-21</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<List<Check_Task>>> GyCheckTasks(string devicename)
        {
            DateTime dt1 = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00");
            DateTime dt2 = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59");
            var model = await checkData.Query(item => item.StartCheckTime >= dt1 && item.StartCheckTime <= dt2 && item.DeviceName == devicename);
            if (model != null && model.Count > 0)
            {
                return MessageModel.CreateSuccessResult(model);
            }
            return MessageModel.CreateFailedResult<List<Check_Task>>("");
        }


    }
}
